package com.treeliked.netdiskdemo.service.impl;

import com.treeliked.netdiskdemo.model.Response;
import com.treeliked.netdiskdemo.model.ResultCode;
import com.treeliked.netdiskdemo.model.dao.FileMapper;
import com.treeliked.netdiskdemo.service.FolderService;
import com.treeliked.netdiskdemo.util.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 文件夹操作服务实现
 *
 * @author lqs2
 * @date 2018/11/29, Thu
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class FolderServiceImpl implements FolderService {

    private final FileMapper fileMapper;

    @Autowired
    public FolderServiceImpl(FileMapper fileMapper) {
        this.fileMapper = fileMapper;

    }

    @Override
    public void createFolder(String path, String folderName, String author, Response response) throws Exception {
        response.setCode(ResultCode.SUCCESS);

        int i = fileMapper.checkFolderExist(path, folderName);
        if (i != 0) {
            response.setMessage("文件夹【" + folderName + "】已经存在，创建失败");
            response.setCode(ResultCode.FAIL);
            return;
        }

        // 创建此文件夹
        com.treeliked.netdiskdemo.model.dataobject.File file1 = new com.treeliked.netdiskdemo.model.dataobject.File();
        file1.setId(IdUtils.get32Id());
        file1.setIsFile(false);
        file1.setAuthor(author);
        file1.setName(folderName);
        file1.setDir(path);
        int insert = fileMapper.insert(file1);
        if (insert == 1) {
            response.setMessage("文件夹【" + folderName + "】创建成功");
            return;
        }
        response.setCode(ResultCode.FAIL);
        response.setMessage("文件夹【" + folderName + "】创建失败");
    }

    @Override
    public void deleteFolder(String path, String folderId, Response response) throws Exception {
        response.setCode(ResultCode.SUCCESS);
        fileMapper.deleteByPath(path);
        fileMapper.deleteByPrimaryKey(folderId);
    }


    @Override
    public List<com.treeliked.netdiskdemo.model.dataobject.File> showFile(String path, String author) throws Exception {
        return fileMapper.selectAllByPath(path, author);
    }


}
